package com.ja10.books;

import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

public class FavoriteEntry {
	
	private Context context = null;
	private SimpleDatabaseHelper helper = null;
	private BookList book = null;
	
	public FavoriteEntry(BookList book, Context context) {
		
		this.context = context;
		this.book = book;
		
		favoriteWrite();
	}
	
	public void favoriteWrite() {
		
		// 日付を取得
		Calendar calendar = Calendar.getInstance();
		String time = String.format("%02d-%02d-%02d",
									calendar.get(Calendar.YEAR),
									calendar.get(Calendar.MONTH)+1,
									calendar.get(Calendar.DATE));
		
		try{
			helper = new SimpleDatabaseHelper(context);
			SQLiteDatabase db = helper.getWritableDatabase();
			
			// 書籍情報をContentValuesに格納
			ContentValues cv = new ContentValues();
			cv.put("genre_name", book.getGenreName());
			cv.put("publisher_name", book.getPublisherName());
			cv.put("title", book.getTitle());
			cv.put("writer", book.getWriter());
			cv.put("content", book.getContent());
			cv.put("record_date", book.getRecordDate());
			cv.put("record_date", time);
			cv.put("publication_date", book.getPublicationDate());
			book.setPictureByte(book.getPictureBmp());	// byte型の画像を設定
			cv.put("picture", book.getPictureByte());
			cv.put("isbn", book.getIsbn());
			
			// ---------お気に入りへの二重登録を調べる
			//　SQL命令を準備
			String[] cols = {"isbn"};
			String[] params = {book.getIsbn()};
			Cursor cs = db.query("myfavorites", cols, "isbn = ?", params, null, null, null, null);
			// 重複がある場合登録せず通知
			if(cs.moveToFirst()){
				Toast.makeText(context, "すでに登録済みです", Toast.LENGTH_SHORT).show();
			}
			// 重複がない場合登録を実行・通知
			else{				
				db.insertWithOnConflict("myfavorites", null, cv, SQLiteDatabase.CONFLICT_REPLACE);	
				Toast.makeText(context, "お気に入りに登録しました", Toast.LENGTH_SHORT).show();
			}
			cs.close();
		} catch(Exception e){
			e.printStackTrace();
		}

	}

}
